﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using CustomersNuke.Scheduling.Utility;
using Quartz;
using Quartz.Impl;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private IScheduler _quartzScheduler;
        
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.instanceName"] = _Constant.InstanceName;
            properties["quartz.scheduler.instanceId"] = _Constant.InstanceId;
            properties["quartz.threadPool.type"] = _Constant.ThreadPoolType;
            properties["quartz.threadPool.threadCount"] = _Constant.ThreadCount;
            properties["quartz.threadPool.threadPriority"] = _Constant.ThreadPriority;
            properties["quartz.jobStore.driverDelegateType"] = _Constant.DriverDelegateType;
            properties["quartz.jobStore.misfireThreshold"] = _Constant.MisfireThreshold;
            properties["quartz.jobStore.type"] = _Constant.JobType;
            properties["quartz.jobStore.useProperties"] = _Constant.UseProperties;
            properties["quartz.jobStore.dataSource"] = _Constant.DataSource;
            properties["quartz.jobStore.tablePrefix"] = _Constant.TablePrefix;
            properties["quartz.jobStore.clustered"] = _Constant.Clustered;
            properties["quartz.jobStore.clusterCheckinInterval"] = _Constant.ClusterCheckinInterval;
            properties["quartz.dataSource.default.connectionString"] = _Constant.ConnectionString;
            properties["quartz.dataSource.default.provider"] = _Constant.Provider;

            ISchedulerFactory schedulerFactory = new StdSchedulerFactory(properties);

            _quartzScheduler = schedulerFactory.GetScheduler();
            _quartzScheduler.Clear();
            IJobDetail job = JobBuilder.Create<MainJob>().WithIdentity("victorJob", "EF").Build();
            ITrigger trigger =
                TriggerBuilder.Create().StartNow().WithIdentity("victorTrigger", "EF").WithSimpleSchedule(
                    x => x.WithIntervalInSeconds(15).WithRepeatCount(3)).Build();

            _quartzScheduler.ScheduleJob(job, trigger);
            _quartzScheduler.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            IJobDetail job = JobBuilder.Create<MainJob>().WithIdentity("victorJob2", "EF").Build();
            ITrigger trigger =
                TriggerBuilder.Create().StartNow().WithIdentity("victorTrigger2", "EF").WithSimpleSchedule(
                    x => x.WithIntervalInSeconds(15).WithRepeatCount(3)).Build();
            _quartzScheduler.ScheduleJob(job, trigger);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string containerNo = "CCLU6766649";//CCLU6766649,CCLU7036368
            string shipName = string.Empty;
            string shipNo = string.Empty;
            LadingResult result = new LadingResult();
            string htmlContent = ParsePage(string.Format("http://edi.easipass.com/dataportal/query.do?ctno={0}&blno=&pagesize=30&submit=%E6%9F%A5%E8%AF%A2&qn=dp_cst_vsl", containerNo));
            if (!string.IsNullOrEmpty(htmlContent))
            {
                string content = HtmlParseUtils.FormatHtml(htmlContent, false, true);
                if (!string.IsNullOrEmpty(content))
                {
                    List<string> headList = HtmlParseUtils.GetSubStrings(content, "<td align=\"left\" bgcolor=\"#[A-Za-z0-9]+\">", null, "</td>", "<td align=\"left\" bgcolor=\"#EEEEEE\">", "<td align=\"left\" bgcolor=\"#E1E1E1\">", "</td>");

                    if (headList != null && headList.Count > 0)
                    {
                        if (headList[0].Contains("<a"))
                        {
                            result.IsSuccess = true;
                            result.IsNeedMoreInfo = true;
                            foreach (string s in headList)
                            {
                                
                            }
                            result.ErrorMessage = "";
                        }
                        else
                        {
                            
                        }


                    }
                }
                else
                {
                    result.IsSuccess = false;
                }
            }

        }

        //private static string GetRealUrl(string htmlContent)
        //{
        //    string content = HtmlParseUtils.FormatHtml(htmlContent, false, true);
        //    string strUrlTemp = string.Empty;
        //    List<string> headList = HtmlParseUtils.GetSubStrings(content, "<td align=\"left\" bgcolor=\"#[A-Za-z0-9]+\">", null, "</td>", "<td align=\"left\" bgcolor=\"#EEEEEE\">", "<td align=\"left\" bgcolor=\"#E1E1E1\">", "</td>");
        //    if (headList != null)
        //    {
        //        for (int i = 0; i < headList.Count / 3; i++)
        //        {
        //            try
        //            {
        //                var doc = new XmlDocument();
        //                doc.LoadXml(headList[3 * i]);
        //                headList[3 * i] = doc.InnerText;
        //                string strVoyageNumber = headList[3 * i + 1];
        //                if (headList[3 * i + 1].Length > 6)
        //                {
        //                    headList[3 * i + 1] = headList[3 * i + 1].Substring(headList[3 * i + 1].Length - 6, 6);
        //                }

        //                var aldTemp = StorageContext.FindOne<ExportDeclaration>(ExportDeclaration.Fields.BillNumber.EQUALS(headList[3 * i + 2]) && ExportDeclaration.Fields.Conveyance.EQUALS(headList[3 * i]) && ExportDeclaration.Fields.VoyageNumber.EQUALS(headList[3 * i + 1]));
        //                if (aldTemp != null)
        //                {
        //                    strUrlTemp = string.Format("http://edi.easipass.com/dataportal/query.do?qn=dp_cst_query_billdetail&blno={0}&vslname={1}&voyage={2}", headList[3 * i + 2], headList[3 * i], strVoyageNumber);
        //                    break;
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                ex.HelpLink = "BillNumber:\"" + headList[3 * i + 2] + "\"\n" + "Context:---" + content + "---";
        //                ExceptionPolicy.HandleException(ex, "NoneExceptionPolicy");
        //            }
        //        }
        //    }
        //    return strUrlTemp;
        //}

        private static bool ParseAdmissionLadingDeclaration(string htmlContent)
        {
            bool successful = false;

            string content = HtmlParseUtils.FormatHtml(htmlContent, false, true);
            if (!string.IsNullOrEmpty(content))
            {
                List<string> NeedMoreInfoHeadList = HtmlParseUtils.GetSubStrings(content, "<td align=\"left\" bgcolor=\"#[A-Za-z0-9]+\">", null, "</td>", "<td align=\"left\" bgcolor=\"#EEEEEE\">", "<td align=\"left\" bgcolor=\"#E1E1E1\">", "</td>");

                if (NeedMoreInfoHeadList != null)
                {
                    if (NeedMoreInfoHeadList[0].Contains("<a"))
                    return successful;
                }

                List<string> headList = HtmlParseUtils.GetSubStrings(content, "<td align=\"left\">", null, "</td>", "<td align=\"left\">", null, "</td>");
                if (headList != null)
                {

                        //var admissionLadingDeclaration = StorageContext.FindOne<AdmissionLadingDeclaration>(AdmissionLadingDeclaration.Fields.BillNumber.EQUALS(headList[2]));
                        //if (admissionLadingDeclaration == null)
                        //{
                        //    admissionLadingDeclaration = new AdmissionLadingDeclaration();
                        //    admissionLadingDeclaration.BillNumber = headList[2];
                        //}
                        //admissionLadingDeclaration.Conveyance = headList[0];
                        //admissionLadingDeclaration.VoyageNumber = headList[1];
                        //admissionLadingDeclaration.GrossWeight = Information.IsNumeric(headList[3]) ? new Decimal?(Decimal.Parse(headList[3])) : null;
                        //admissionLadingDeclaration.PackageAmount = Information.IsNumeric(headList[4]) ? new int?(int.Parse(headList[4])) : null;
                        //admissionLadingDeclaration.Html = content;
                        //admissionLadingDeclaration.Save();
                        ////add detail
                        //List<string> detailList = HtmlParseUtils.GetSubStrings(content, "<tr height=\"21\">", null, "</tr>", null, null, null);
                        //foreach (string s in detailList)
                        //{
                        //    List<string> list = HtmlParseUtils.GetSubStrings(s, "<td align=\"left\" bgcolor=\"#[A-Za-z0-9]+\">", null, "</td>", "<td align=\"left\" bgcolor=\"#EEEEEE\">", "<td align=\"left\" bgcolor=\"#E1E1E1\">", "</td>");
                        //    if (list != null)
                        //    {
                        //        try
                        //        {
                        //            var admissionLadingDeclarationContainer = StorageContext.FindOne<AdmissionLadingDeclarationContainer>(AdmissionLadingDeclarationContainer.Fields.BillNumber.EQUALS(headList[2]) && AdmissionLadingDeclarationContainer.Fields.Number.EQUALS(list[0]));
                        //            if (admissionLadingDeclarationContainer == null)
                        //            {
                        //                admissionLadingDeclarationContainer = new AdmissionLadingDeclarationContainer();
                        //                admissionLadingDeclarationContainer.BillNumber = headList[2];
                        //                admissionLadingDeclarationContainer.Number = list[0];
                        //            }
                        //            admissionLadingDeclarationContainer.GrossWeight = Information.IsNumeric(list[1]) ? new Decimal?(Decimal.Parse(list[1])) : null;
                        //            admissionLadingDeclarationContainer.PackageAmount = Information.IsNumeric(list[1]) ? new int?(int.Parse(list[2])) : null;
                        //            admissionLadingDeclarationContainer.ReturnReceiptDescription = list[3];
                        //            string strNewDateTime = list[4].Substring(0, 4) + "-" + list[4].Substring(4, 2) + "-" + list[4].Substring(6, 2) + " " + list[4].Substring(8, 2) + ":" + list[4].Substring(10, 2) + ":00";
                        //            admissionLadingDeclarationContainer.ReceivedReturnReceiptDateTime = Information.IsDate(strNewDateTime) ? new DateTime?(DateTime.Parse(strNewDateTime)) : null;
                        //            admissionLadingDeclarationContainer.Owner = list[5];
                        //            admissionLadingDeclarationContainer.UnladingPortCode = list[6];
                        //            admissionLadingDeclarationContainer.COSTRPNumber = list[7];
                        //            admissionLadingDeclarationContainer.Html = s;

                        //            _itemForSaveList.Add(admissionLadingDeclarationContainer);
                        //            //admissionLadingDeclarationContainer.Save();
                        //        }
                        //        catch (Exception ex)
                        //        {
                        //            ex.HelpLink = "BillNumber:\"" + headList[2] + "\" Number:\"" + list[0] + "\"";
                        //            ExceptionPolicy.HandleException(ex, "NoneExceptionPolicy");
                        //        }
                        //    }
                        //}
                        successful = true;
                   
                }
            }
            return successful;
        }
        private static string ParsePage(string url)
        {
            try
            {
                var web = new WebClient();
                web.Encoding = Encoding.UTF8;
                //WebProxy proxy = new WebProxy("http://jpnproxy.fareast.corp.microsoft.com:80/", true);
                //web.Proxy = proxy;
                string content = HtmlParseUtils.FormatHtml(web.DownloadString(url), false, true);
                return content;
            }
            catch (Exception ex)
            {
                ex.HelpLink = url;
                return null;
            }
        }
    }

    public class MainJob : IInterruptableJob
    {
        private bool interrupted;
        public void Execute(IJobExecutionContext context)
        {
            if (!interrupted)
            {
                MessageBox.Show(context.JobDetail.Key.Name);
                //context.Scheduler.UnscheduleJob(context.Trigger.Key);
            }
        }

        public void Interrupt()
        {
            interrupted = true;
        }
    }

    public static class _Constant
    {
        public static string InstanceName = "CustomsNukeScheduler";
        public static string InstanceId = "CustomsNukeInstance";
        public static string ThreadPoolType = "Quartz.Simpl.SimpleThreadPool, Quartz";
        public static string ThreadCount = "10";
        public static string ThreadPriority = "Normal";
        public static string DriverDelegateType = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
        public static string MisfireThreshold = "60000";
        public static string JobType = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
        public static string UseProperties = "false";
        public static string DataSource = "default";
        public static string TablePrefix = "QRTZ_";
        public static string Clustered = "true";
        public static string ClusterCheckinInterval = "1000";
        public static string ConnectionString = "Server=(local);Database=quartz;Trusted_Connection=True; MultipleActiveResultSets=True";
        public static string Provider = "SqlServer-20";
    }
}
